package com.fingard.dsp.bank.directbank.crbc01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.dsp.bank.directbank.crbc01.util.HttpDownload;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.util.TransIDHelper;
import com.fingard.util.secret.salary.FieldHiddenUtil;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;


public class CRBC01Base extends DirectBase implements ITcpClient {
    private static TransIDHelper idHelper = new TransIDHelper(1, 99);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.Time6Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }


    protected void writeCommonHeader(XmlTextWriter xmlWriter,CRBC01Header bankHeader) throws Exception {
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement("CRBANK");
        xmlWriter.writeStartElement("HEAD");
        xmlWriter.writeElementString("TRAN_CODE", bankHeader.tranCode);                                 //交易码
        xmlWriter.writeElementString("TRAN_TIME", Format.DateTime14Format.format(bankHeader.tranTime));  //交易时间
        xmlWriter.writeEndElement();
    }

    protected String[] sendToBank(String p_reqStr) throws Exception {
//        //一：参数、对象定义
//        String[] retStrArr = new String[]{"", ""};
//        String tmpCharset = getCharset();
//        WriteBankLogLn("1.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);
//        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
//
//        //二：发送报文
//        WriteBankLogStep2(p_reqStr);
//        TcpReceiver tmpReceiver = tmpClient.sendMessage(p_reqStr.getBytes(tmpCharset));
//
//        //三：解析报文
//        if (StringHelper.isNullOrEmpty(tmpReceiver.connState)) {
//            String tmpBkStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
//            WriteBankLogStep3(tmpBkStr);
//        }
//        retStrArr[0] = tmpReceiver.connState;
//        if (tmpReceiver.isCompleted) {
//            retStrArr[1] = new String(tmpReceiver.recBytes, tmpReceiver.contentStartIndex, tmpReceiver.contentLength, tmpCharset);
//        } else {
//            retStrArr[1] = tmpReceiver.getConnMsg();
//            WriteBankLogLn(retStrArr[1]);
//        }

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverURL);
        if(isNeedHiddleField){
            WriteBankLogStep2(FieldHiddenUtil.amountHiddle(p_reqStr,new String[]{"TOTAL_AMT"}));
        }else{
            WriteBankLogStep2(p_reqStr);
        }
        WebRequest tmpWebRequest = new WebRequest(bankFront.serverURL);
        tmpWebRequest.setBankFront(this.bankFront);
        tmpWebRequest.setConnectTimeout(10000);

        tmpWebRequest.setReadTimeout(10000);
        tmpWebRequest.setRequestProperty("connection", "Close");

        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        String[] retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
        boolean enableSalaryDecrypt = getBankConfig().getValueAsBool("enableSalaryDecrypt");
        if(enableSalaryDecrypt){
            WriteBankLogStep3(FieldHiddenUtil.amountHiddle(retStr[1],new String[]{"TOTAL_AMT"}));
        }else{
            WriteBankLogStep3(retStr[1]);
        }
        if (retStr[0].length() == 0) {
            int tmpIndex = retStr[1].indexOf("<");
            if (tmpIndex > 0) {
                retStr[1] = retStr[1].substring(tmpIndex);
            }
        }

        return retStr;
    }
    protected void sendToBank2(String cust_account, String queryDate) throws Exception {

        String serverURL = bankFront.serverURL.substring(0, bankFront.serverURL.lastIndexOf('/')) +
                "/download?action=200007EProofDownload&cust_account=" + cust_account + "&queryDate=" + queryDate;
        WriteBankLogLn("2.提交银行的地址：" + serverURL);
        String root = FGBiz.dspCenter.dspSet.receiptMainDir + File.separator + bankFront.bankCode + "Receipt" + File.separator;
        String fileName = cust_account + "_" + queryDate + ".zip";
        File file = new File(root + fileName);
        if (!file.exists()) {
            WriteBankLogLn("3.执行" + fileName + "文件下载...");
            WriteBankLogLn(HttpDownload.download(serverURL, root));
        } else {
            WriteBankLogLn("3.文件" + root + fileName + "已存在，即账号" + cust_account + "在交易日期" + queryDate
                    + "电子回单已下载，无需重复下载，如需再次下载删除本文件即可");
        }
    }
    //上送格式为json格式
    protected  String[] sendToATS(String jsonData) throws Exception{
        String[] retStr = new String[]{"",""};
        WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);


        //发送ATS
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(60000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        String charsetName = getCharset();
        WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
        byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据"+retStr[1]);

        return retStr;
    }
    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected String getCharset(String p_def, String p_for){
        return getBankConfig().getCharset(p_def, p_for);
    }

    @Override
    public void getContentLength(TcpReceiver tcpReceiver) throws Exception {

    }

    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("000000")) {
                return true;
            }
        }
        return false;
    }
}
